package com.kunka.shiro.realm;





import com.kunka.api.entity.system.TSysUser;
import com.kunka.api.service.service.login.LoginService;
import com.kunka.utils.SpringBeanFactoryUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;


/**
 *   shiro 的 Realm 类
 *   自定义校验用户逻辑
 *
 */

public class LoginRealm extends AuthorizingRealm {


    /**
     * 认证权限
     *
     * 暂时不验证
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //添加角色和权限
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        /* TSysUser userInfo = (TSysUser) principalCollection.getPrimaryPrincipal();

       for (SysRole role: userInfo.getRoleList()) {
            authorizationInfo.addRole(role.getRole());
            for (SysPermission p: role.getPermissions()) {
                authorizationInfo.addStringPermission(p.getPermission());
            }
        }*/



        return authorizationInfo;
    }



    /**
     * 认证用户
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户的Token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //得到用户名
        String userCode = token.getUsername();

        LoginService loginService = SpringBeanFactoryUtils.getBean("loginService",LoginService.class);
        //通过code 查询用户
        TSysUser userInfo = loginService.getUserByCode(userCode);
        //校验用户是否存在
        if(userInfo == null) {
            throw new IncorrectCredentialsException("用户名或密码不正确");
        }
        //这边shiro框架校验用户名以及密码
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                userInfo, userInfo.getRPassword(), getName());
         return authenticationInfo;
    }
}
